package com.example.demo_scan;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageButton;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.zxing.client.result.AddressBookParsedResult;
import com.google.zxing.client.result.ParsedResultType;
import com.google.zxing.client.result.URIParsedResult;
import com.mylhyl.zxing.scanner.OnScannerCompletionListener;
import com.mylhyl.zxing.scanner.ScannerView;
import com.google.zxing.client.result.ParsedResult;

import javax.xml.transform.Result;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;

public class QRCodeActivity extends FlutterActivity implements OnScannerCompletionListener {

    private CommonTitleBar titleBar;

    // 传感器管理器
    private SensorManager sensorManager;

    private ScannerView mScannerView;

    // 手电筒
    private ImageButton lightImageButton;

    // 手电筒tag: 1关闭，2打开
    private int lightTag = 1;

    private View lightBtn;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_qrcode);

        // 获取感应器服务
        sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        // 获取光线传感器
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        // 注册监听器
        sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
        // 页面初始化
        initWithConfigQRCodeView();

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
    }

    /**
     * 页面初始化
     * */
    private void initWithConfigQRCodeView()  {
        titleBar = findViewById(R.id.title_view);
        titleBar.setTitleView("扫码二维码");
        titleBar.setOnclickListener(new CommonTitleBar.OnclickListener() {
            @Override
            public void clickLeft() {
                finish();
            }

            @Override
            public void clickRight() {

            }
        });

        // 扫描二维码视图
        mScannerView = findViewById(R.id.scanner_qrcode);
        mScannerView.setOnScannerCompletionListener(this);

        // 开启闪光灯
        mScannerView.toggleLight(false); // 关

        // 手电筒
        lightImageButton = findViewById(R.id.imageButton_qrcodeLight);
        lightImageButton.setVisibility(View.VISIBLE);

        lightBtn = findViewById(R.id.tap_light);
        lightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (lightTag == 1) {
                    lightTag = 2;
                    mScannerView.toggleLight(true);
                    lightImageButton.setImageResource(R.drawable.icon_scan_illumination);
                } else if (lightTag == 2) {
                    lightTag = 1;
                    mScannerView.toggleLight(false);
                    lightImageButton.setImageResource(R.drawable.icon_scan_illumination_normal);
                }
            }
        });
    }

    /**
     ****** 当前Activity由被覆盖状态回到前台或解锁屏：系统会调用onResume方法，再次进入运行状态
     * */
    @Override
    protected void onResume() {
        mScannerView.onResume();
        super.onResume();
    }

    /**
     ****** 当前Activity被其他Activity覆盖其上或被锁屏：系统会调用onPause方法，暂停当前Activity的执行。
     * */
    @Override
    protected void onPause() {
        mScannerView.onPause();
        super.onPause();
    }

    // 获取亮度
    private int getSystemBrightness() {
        int systemBrightness = 0;
        try {
            systemBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {

        }
        return systemBrightness;
    }

    private SensorEventListener listener = new SensorEventListener() {
        // 当传感器监测到的数值变化时
        @Override
        public void onSensorChanged(SensorEvent event) {
            // values 数组中第一个值就是当前的光照强度
            float value = event.values[0];
            //EBLog.d("亮度", String.valueOf(value));
        }

        // 当传感器精度发生变化
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    /**
     * 扫描成功后将调用
     *
     * @param result    扫描结果
     * @param parsedResult 结果类型
     * @param bitmap      扫描后的图像
     * */
    @Override
    public void onScannerCompletion(com.google.zxing.Result result, ParsedResult parsedResult, Bitmap bitmap) {
        ParsedResultType type = parsedResult.getType();
        switch (type) {
            case ADDRESSBOOK:
                AddressBookParsedResult addressBookParsedResult = (AddressBookParsedResult)parsedResult;
                finish();
                break;
            case URI:
                URIParsedResult uriParsedResult = (URIParsedResult)parsedResult;
                uriParsedResult.toString();
                finish();
                break;
            case TEXT:
                scan(parsedResult.toString());
                //finish();
                break;
            default:
                break;
        }
    }

    private void scan(String string) {
        mScannerView.onPause();

        // 截取@@之后的字符串
        String prefixStr = string.substring(string.indexOf("@@"));
        // 去除@@后的字符串
        String noString = prefixStr.substring(2, prefixStr.length());
        // 去除+++ ---
        String str = noString.substring(0, noString.length() - 3);
        final String flagString = noString.substring(noString.length() - 3,noString.length());

        System.out.println(flagString);
    }

}